package utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import entity.LogCenterBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author weijianyu
 */
public class HttpClientUtil {
    private static final Logger logger = LogManager.getLogger(HttpClientUtil.class);
    private static final int SUCCESS = 200;
    private static final CookieStore cookieStore = new BasicCookieStore();

    static {
        Map<String, String> maps = Maps.newHashMap();
        maps.put("skmtutc", "371LzFclTrL8q8dDErKC73+tTTSputk2UDHYje1w/yryKc5ELEXGH5x47a7qjJAd-CukVGjhTlsWbyQR/3FvajPReFpE=");
        maps.put("_ga", "GA1.2.789267282.1523846661");
        maps.put("_gid", "GA1.2.335499209.1523846661");
        maps.put("_lxsdk_cuid", "162cc605c71c8-0451914bffb306-33697b04-1fa400-162cc605c71c8");
        maps.put("_lxsdk", "162cc605c71c8-0451914bffb306-33697b04-1fa400-162cc605c71c8");
        maps.put("al", "zuljmnmuvztaujafglnkbolkxtcqkhka");
        maps.put("u", "1315399");
        maps.put("uu", "a1ab5000-4178-11e8-b724-a10eb6b97b0b");
        maps.put("cid", "1");
        maps.put("ai", "1");
        maps.put("lc_sid", "07f4d3b934*04ad09b3251a79deab984");
        maps.put("sessionid", "be8ebmm75c3p3va55hdf1p051uf35afh");
        maps.put("csrftoken", "2zn1GaYWOBiZSksznDxLpQIN6h09shQL");

        Set<Map.Entry<String, String>> cookieMaps = maps.entrySet();
        for (Map.Entry<String, String> cookieMap : cookieMaps) {
            BasicClientCookie basicClientCookie = new BasicClientCookie(cookieMap.getKey(), cookieMap.getValue());
            basicClientCookie.setVersion(0);
            basicClientCookie.setDomain("/");
            basicClientCookie.setPath("/");
            cookieStore.addCookie(basicClientCookie);
        }
    }

    private HttpClientUtil() {
    }

    private static CloseableHttpClient getDefaultHttpClient() {
        return HttpClients.custom()
                .setDefaultCookieStore(cookieStore).build();
    }

    private static RequestConfig defaultConfig() {
        return RequestConfig.custom().
                setConnectTimeout(3000).setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000).setRedirectsEnabled(true).build();
    }

    /**
     * post 请求
     *
     * @param url
     * @param body
     * @return
     */
    public static String post(String url, LogCenterBody body) {
        CloseableHttpClient httpClient = getDefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            post.setConfig(defaultConfig());
            post.setEntity(new StringEntity(JSONObject.toJSONString(body), "UTF-8"));
            setDefaultHeader(post);
            HttpResponse response = httpClient.execute(post);
            if (response != null && response.getStatusLine().getStatusCode() == SUCCESS) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            logger.error("httpClient post error", e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("httpClient close error", e);
            }
        }
        return StringUtils.EMPTY;
    }

    private static void setDefaultHeader(HttpPost post) {
        post.setHeader("Host", "logcenter.data.sankuai.com");
        post.setHeader("Accept", "application/json, text/plain, */*");
        post.setHeader("Origin", "http://logcenter.data.sankuai.com");
        post.setHeader("X-CSRFToken", "2zn1GaYWOBiZSksznDxLpQIN6h09shQL");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        post.setHeader("Referer", "http://logcenter.data.sankuai.com/");
        post.setHeader("Accept-Encoding", "gzip, deflate");
        post.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        post.setHeader("Cookie", "skmtutc=371LzFclTrL8q8dDErKC73+tTTSputk2UDHYje1w/yryKc5ELEXGH5x47a7qjJAd-CukVGjhTlsWbyQR/3FvajPReFpE=; _ga=GA1.2.789267282.1523846661; _gid=GA1.2.335499209.1523846661; _lxsdk_cuid=162cc605c71c8-0451914bffb306-33697b04-1fa400-162cc605c71c8; _lxsdk=162cc605c71c8-0451914bffb306-33697b04-1fa400-162cc605c71c8; al=zuljmnmuvztaujafglnkbolkxtcqkhka; u=1315399; uu=a1ab5000-4178-11e8-b724-a10eb6b97b0b; cid=1; ai=1; lc_sid=07f4d3b934*04ad09b3251a79deab984; sessionid=be8ebmm75c3p3va55hdf1p051uf35afh; csrftoken=2zn1GaYWOBiZSksznDxLpQIN6h09shQL");
    }
}
